<?php

if ( $argc <= 3 ) {
    print "Missing argument(s). Proper format is:\n\n";
    print "php $argv[0] [Web Server URL] [New Status] [Today's Position: [middle|bottom]]\n\n";
    exit(1);
}

$webServerUrl = $argv[1];
$newStatus = $argv[2];
$todaysPosition = $argv[3];

//Read image ids
if ( $imageInfosAsString = file_get_contents($webServerUrl . '/php/get_image_infos.php') ) {

    $imageInfos = split("\n", $imageInfosAsString);
    
    //Determine bottom date for the initial publish date
    $oneDay = new DateInterval('P1D');
    $publishDate = new DateTime();
    if ( $todaysPosition == 'middle' ) {
        for ( $i = 0; $i < count($imageInfos) / 6; $i++ ) {
            $publishDate->sub($oneDay);
        }
    }
    
    for ( $i = 0; $i < count($imageInfos); $i++ ) {
    
        //Retrieve record IDs
        $imageFields = split("\|", $imageInfos[$i]);
        $id = $imageFields[0];
        print $imageInfos[$i] . "\n";

        //Update the record        
    	$docurl = curl_init();
    	curl_setopt($docurl, CURLOPT_SSL_VERIFYPEER, false);
    	curl_setopt($docurl, CURLOPT_URL, $webServerUrl . '/php/admin/set_image_info.php');
    	curl_setopt($docurl, CURLOPT_VERBOSE, FALSE);
    	curl_setopt($docurl, CURLOPT_HEADER, 1);
    	curl_setopt($docurl, CURLOPT_POST, 1);
    	curl_setopt($docurl, CURLOPT_RETURNTRANSFER, 1);
    	curl_setopt($docurl, CURLOPT_FOLLOWLOCATION, 1);
    	curl_setopt($docurl, CURLOPT_POSTFIELDS, array( 'ii_id'=>$id,
                                                        'ii_description'=>$imageFields[1],
							'ii_source'=>$imageFields[2],
                                                        'ii_submit_date'=>$imageFields[3],
                                                        'ii_status'=>$newStatus,
                                                        'ii_publish_date'=>$publishDate->format('Y-m-d'),
                                                        'ii_email'=>$imageFields[6],
                                                        'ii_comment'=>$imageFields[7]));
    	$webpage = curl_exec($docurl); 
    	curl_close($docurl);
        
        //Increment the publish date after every 3 images
        if ( ($i + 1) % 3 == 0 ) { 
            $publishDate->add($oneDay);
        }
    }    
}
else {
    print 'Unable to retrieve image ids from ' . $webServerUrl . "\n";
}
?>